from rest_framework.serializers import ModelSerializer
from rest_framework_jwt.settings import api_settings

from .models import User
from rest_framework import serializers
import re
from django_redis import get_redis_connection


class RegisterCreateSerializer(ModelSerializer):
    password2 = serializers.CharField(label='验证密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(label="是否同意协议", allow_null=False, allow_blank=False, write_only=True)
    token = serializers.CharField(label='登陆令牌', read_only=True)

    class Meta():
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow', 'token')
        # 添加额外参数
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 验证
    def validate_mobile(self, value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError("手机号码错误")
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError("未同意协议")
        return value

    def validate(self, attrs):
        password = attrs.get('password')
        password2 = attrs.get('password2')

        if password != password2:
            raise serializers.ValidationError('两次密码输入不一致')

        code = attrs.get('sms_code')
        redis_conn = get_redis_connection("code")
        mobile = attrs.get("mobile")
        redis_code = redis_conn.get('sms_%s' % mobile)

        if redis_code == None:
            raise serializers.ValidationError('短信验证码失效')
        if redis_code.decode() != code:
            raise serializers.ValidationError('短信验证码不正确')

        return attrs

    # 创建入库
    def create(self, validated_data):

        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)
        # 密码加密保存
        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


class UserDetailSerializer(ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = validated_data['email']
        instance.save()

        # 发送激活邮件
        # 生成激活链接
        verify_url = instance.generate_verify_email_url()
        # 发送,注意调用delay方法
        from celery_task.email.tasks import send_verify_mail
        send_verify_mail.delay(email, verify_url)
        return instance
